package com.topisv.tms.web.stock.instorage;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.dto.OutstorageInfoDto;
import com.topisv.tms.entity.work.ViewWorkOrder;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.mybatis.Pagination;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.vo.QueryOutstorageInfoVO;
import com.topisv.tms.service.work.ViewWorkOrderService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.tools.ExcelStUtil;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 出库信息
 * @author ch
 *
 */
@Controller
@RequestMapping(value = "/outstorageInfo_1")
public class OutstorageInfo1Controller extends BaseDataTableController {

	private static final Logger logger = LoggerFactory.getLogger(OutstorageInfo1Controller.class);

	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private ViewWorkOrderService viewWorkOrderService;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private ShopSourceService shopSourceService;
	
	
	//导向出库信息页面
	@RequestMapping(value = "v2_toOutstorageInfoPage")
	public String toOutstorageInfoPage(Model model, ServletRequest request) {
		try {
		    fillSelectValue(model, null);
			//当前用户关联的商家列表
			ShiroUser curUser = getShiroUser();
			
			//如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				String customerCode=curUser.customerCode;
				//初始化店铺数据
				if(StringUtils.isNotBlank(customerCode)){
					List<ShopSource> shopList=this.shopSourceService.findByCustomerCode(customerCode);
					model.addAttribute("shopList", shopList);
				}
			}
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "instorage/outstorageInfo_1";
	}
	
	
    //////////////////////////////////////////////////////////出库数据合计///////////////////////////////////////////////////////////////////////
	
    /**
     * 查询出库信息列表(分页)
     * 
     * @param OSInfo 页面查询条件
     * @return 
     * @throws 
     * @author <a href=mailto:libin@nryuncang.com>libin</a>
     * @version 0.0.16
     */
    @RequestMapping(value = "v2_queryOutstorageInfo")
    @ResponseBody
    public Object queryOutstorageInfo(QueryOutstorageInfoVO OSInfo) {
        Pagination page = null;
        try {
            OSInfo.setStatus("countStock");
            OSInfo.setFromDate(OSInfo.getFromDate()+" 00:00:00");
            OSInfo.setToDate(OSInfo.getToDate()+" 23:59:59");
            
            page = viewWorkOrderService.getPageOutstorageInfo(OSInfo);
        } catch (Exception e) {
            logger.error("error", e);
        }
        return page;
    }
	 
	//查询出库信息
    @Deprecated
	@RequestMapping(value = "v2_queryOutstorageInfobak")
	public String queryOutstorageInfobak(Model model, ServletRequest request) {
		try {
			
			//当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode=(String)param.get("warehouseCode");
			String batchCode=(String)param.get("batchCode");
			String taskCode=(String)param.get("taskCode");
			String sku=(String)param.get("sku");
			String shopCode=(String)param.get("shopCode");
			
			//时间筛选
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");

			//筛选时间为空时，不查询直接返回
			if(StringUtils.isEmpty(fromDateStr) || StringUtils.isEmpty(toDateStr)){
			    return "instorage/outstorageInfo_1";
			}
			
			if(StringUtils.isNotEmpty(fromDateStr)){
			    param.put("fromDate", fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
			    param.put("toDate", toDateStr+" 23:59:59");
			}
			
			param.put("status", "countStock");
//			param.put("cancelStatus", "ok");
			
			//初始化仓库数据
			String customerCode=(String)param.get("customerCode");
			List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
			model.addAttribute("warehouseList", warehouseList); 
			
			//初始化店铺数据
			List<ShopSource> shopList=this.shopSourceService.findByCustomerCode(customerCode);
			model.addAttribute("shopList", shopList);
			
			//出库信息统计
			/** begin modify 调用重写过后的方法 2016-06-16 lianghe.yuan */

			//List<OutstorageInfoDto> dtoList=this.viewWorkOrderService.loadDtoByParam(param);
            List<Object[]> resultList = this.viewWorkOrderService.loadDtoByParamNew(param);
            
            List<OutstorageInfoDto> dtoList = new ArrayList<OutstorageInfoDto>(resultList.size());
            for (Object[] objects : resultList) {
                OutstorageInfoDto dto = new OutstorageInfoDto();
                
                Customers cus = new Customers();
                cus.setCustomerName((String) objects[0]);
                dto.setCustomer(cus);
                
                AreaGroup warehouse = new AreaGroup();
                warehouse.setGroupName((String) objects[1]);
                dto.setWarehouse(warehouse);
                
                dto.setSku((String) objects[2]);
                dto.setGoodsName((String) objects[3]);
                
                dto.setNormalNum(((BigDecimal) objects[4]).intValue());
                dto.setUlOrderNum(((BigDecimal) objects[5]).intValue());
                dto.setRecallNum(((BigDecimal) objects[6]).intValue());
                dto.setExceptionNum(((BigDecimal) objects[7]).intValue());
                dto.setAllotNum(((BigDecimal) objects[8]).intValue());
                dto.setSaleNum(((BigDecimal) objects[9]).intValue());
                dto.setReturnNum(((BigDecimal) objects[10]).intValue());
                dto.setNum(((BigDecimal) objects[11]).intValue());
                
                dtoList.add(dto);
            }
            /** end modify 调用重写过后的方法 2016-06-16 lianghe.yuan */

            model.addAttribute("dtoList", dtoList);
			
			model.addAttribute("_customerCode", customerCode);
			model.addAttribute("_warehouseCode", warehouseCode);
			model.addAttribute("_batchCode", batchCode);
			model.addAttribute("_taskCode", taskCode);
			model.addAttribute("_sku", sku);
			model.addAttribute("_fromDate", fromDateStr);
			model.addAttribute("_toDate", toDateStr);
			model.addAttribute("_shopCode", shopCode);
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		
		return "instorage/outstorageInfo_1";
	}
	
	/**
	 * 导出_出库数据统计
	 */
	@RequestMapping(value = "expTotal")
	public String expTotal(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
//			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//出库信息统计
			//Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "");
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");

			//筛选时间为空时，不查询直接返回
			if(StringUtils.isEmpty(fromDateStr) || StringUtils.isEmpty(toDateStr)){
			    return null;
			}

			if(StringUtils.isNotEmpty(fromDateStr)){
			    param.put("fromDate", fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
			    param.put("toDate", toDateStr+" 23:59:59");
			}
			
			param.put("status", "countStock");
//			param.put("cancelStatus", "ok");
			
			/** begin modify 调用重写过后的方法 2016-06-16 lianghe.yuan */
			
			//List<OutstorageInfoDto> dtoList=this.viewWorkOrderService.loadDtoByParam(param);
			List<Object[]> list = this.viewWorkOrderService.loadDtoByParamNew(param);
			
			
			/** 定义导出数据集合 */
			// comment 2016-06-16
			/*List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < dtoList.size(); i++) {
				try {
					OutstorageInfoDto o=dtoList.get(i);
					Object[] obj = {
							i+1,
							o.getCustomer().getCustomerName(),
							o.getWarehouse()!=null?o.getWarehouse().getGroupName():"",
							o.getSku(),
							o.getGoodsName(),
							o.getNormalNum(),
							o.getUlOrderNum(),
							o.getRecallNum(),
							o.getExceptionNum(),
							o.getAllotNum(),
							o.getSaleNum(),
							o.getReturnNum(),
							o.getNum(),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					logger.error("error",e);
				}
			}*/
			
			/** end modify 调用重写过后的方法 2016-06-16 lianghe.yuan */
			
			/** begin modify 导出修改 2016-06-16 lianghe.yuan */
			/** 导出数据 */
			/** begin old 2016-06-16 */
//			String[] title = { "序号", "商家","仓库","SKU","商品名称","订单数量","线下单数量","重发数量","异常单数","调拨数量","销售出库数","返厂数量","合计"};
//			String filepath = "OutStorageInfo.xls";
//			String title_page="出库数据统计";
//			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
//			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"utf-8"));
//			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
//			byte[] fb = new byte[f.available()];
//			f.read(fb);
//			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
//			output =((HttpServletResponse)response).getOutputStream();
//			int by = 0;
//			while ((by = bais.read()) != -1) {
//				output.write(by);
//			}
//			output.flush();
			/** end old 2016-06-16 */
			
			
			/** begin new 2016-06-16 */
			output = response.getOutputStream();
			
			response.setContentType("application/octet-stream");
            String[] titles = { "商家", "仓库", "SKU", "商品名称", "订单数量", "线下单数量", "重发数量", "异常单数", "调拨数量", "销售出库数", "返厂数量", "合计" };
            String fileName = new String(("OutStorageInfo.xls").getBytes("GBK"), "ISO8859-1");
            ((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename=" + fileName);
            
            String pageTitle="出库数据统计";
            
            ExcelStUtil.export(output, DateFormatUtils.format(now, "yyyyMMddhhmmss"), pageTitle, titles, list);
			/** end new 2016-06-16 */
			
			/** begin modify 导出修改 2016-06-16 lianghe.yuan */
		} catch (Exception e) {
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	//////////////////////////////////////////////////////////订单明细///////////////////////////////////////////////////////////////////////
	
	//查询订单明细
	@RequestMapping(value = "v2_queryDetail_order")
	public String queryDetail_order(Model model, ServletRequest request) {
		try {
			
			//Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
		    Map<String, Object> param = Servlets.getParametersStartingWith(request, "");
			String customerCode=(String)param.get("customerCode");
			String warehouseCode=(String)param.get("warehouseCode");
			String batchCode=(String)param.get("batchCode");
			String taskCode=(String)param.get("taskCode");
			String sku=(String)param.get("sku");
			String shopCode=(String)param.get("shopCode");
			
			//时间筛选
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			
			//筛选时间为空时，不查询直接返回
			if(StringUtils.isEmpty(fromDateStr) || StringUtils.isEmpty(toDateStr)){
				return "instorage/outstorageInfo_detail_order";
			}
			
            if (StringUtils.isNotEmpty(fromDateStr)) {
                param.put("fromDate", fromDateStr + " 00:00:00");
            }
            if (StringUtils.isNotEmpty(toDateStr)) {
                param.put("toDate", toDateStr + " 23:59:59");
            }
			param.put("status", "countStock");
//			param.put("cancelStatus", "ok");
			
			
			//出库信息统计
			/** begin modify 改用SQL调用 20160616 liangeh.yuan */
			//List<ViewWorkOrder> infoList=this.viewWorkOrderService.loadByParam(param);
			List<Object[]> resultList = this.viewWorkOrderService.loadByParamNew(param);
			if(resultList.size()<1){//add LiBin 20160808 方便打日志
			    logger.info("订单明细的查询参数是{}.", param);  
			}
			List<ViewWorkOrder> infoList = new ArrayList<ViewWorkOrder>(resultList.size());
			
			for (Object[] objects : resultList) {
			    ViewWorkOrder v = new ViewWorkOrder();

			    Customers cus = new Customers();
                cus.setCustomerName((String) objects[1]);
                v.setCustomer(cus);
                
                v.setShopName((String) objects[2]);
                
                AreaGroup warehouse = new AreaGroup();
                warehouse.setGroupName((String) objects[3]);
                v.setWarehouse(warehouse);
                
                v.setBatchCode((String) objects[4]);
                v.setTaskCode((String) objects[5]);
                v.setOrderno((String) objects[6]);
                v.setOrderType((String) objects[7]);
                v.setSku((String) objects[8]);
                v.setGoodsName((String) objects[9]);
                v.setExpressNo((String) objects[10]);
                v.setCustomerOrderno((String) objects[11]);
                v.setFromno((String) objects[12]);
                v.setAddres((String) objects[13]);
                v.setNum((Integer) objects[14]);
                
                BigDecimal price = (BigDecimal) objects[15];
                v.setPri(price == null ? null : price.doubleValue());
                
                v.setCancelStatus((String) objects[16]);
                v.setCreateTime((Date) objects[17]);
			    
			    infoList.add(v);
			}
			
			/** end modify 改用SQL调用 20160616 liangeh.yuan */
			
			model.addAttribute("infoList", infoList);
			
			model.addAttribute("_customerCode", customerCode);
			model.addAttribute("_warehouseCode", warehouseCode);
			model.addAttribute("_fromDate", fromDateStr);
			model.addAttribute("_toDate", toDateStr);
			model.addAttribute("_batchCode", batchCode);
			model.addAttribute("_taskCode", taskCode);
			model.addAttribute("_sku", sku);
			model.addAttribute("_shopCode", shopCode);
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		
		return "instorage/outstorageInfo_detail_order";
	}
	
	/**
	 * 导出_订单明细
	 */
	@RequestMapping(value = "expDetail_order")
	public String expDetail_order(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
//			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//出库信息统计
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			String customerCode=(String) param.get("customerCode");
			String warehouseCode=(String) param.get("warehouseCode");
			
			//筛选时间为空时，不查询直接返回
			if(StringUtils.isEmpty(fromDateStr) || StringUtils.isEmpty(toDateStr)){
			    return null;
			}

			if(StringUtils.isNotEmpty(fromDateStr)){
			    param.put("fromDate", fromDateStr + " 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
			    param.put("toDate", toDateStr+" 23:59:59");
			}
			
			param.put("status", "countStock");
//			param.put("cancelStatus", "ok");
			
			/** begin modify 20160616 lianghe.yuan */
			//List<ViewWorkOrder> infoList=this.viewWorkOrderService.loadByParam(param);
			List<Object[]> list = this.viewWorkOrderService.loadByParamNew(param);
			if(list.size()<1){//add LiBin 20160808 方便打日志
			    logger.info("导出订单明细的查询参数是{}.", param);
			}
			
			/** 定义导出数据集合 */
			/*
			List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < infoList.size(); i++) {
				try {
					ViewWorkOrder o=infoList.get(i);
					String cancelOrder=o.getCancelStatus();
					String cancelOrderStr="";
					if("cancel".equals(cancelOrder)){
						cancelOrderStr="取消单";
					}else if("refuse".equals(cancelOrder)){
						cancelOrderStr="拒收单";
					}else if("change".equals(cancelOrder)){
						cancelOrderStr="换货单";
					}else if("ok".equals(cancelOrder)){
						cancelOrderStr="正常单";
					}else if("outScope".equals(cancelOrder)){
						cancelOrderStr="超区件";
					}else if("lose".equals(cancelOrder)){
						cancelOrderStr="丢件单";
					}
					
					EdiGoodsSku goodsSku = ediGoodsSkuService.findByCustomerCodeAndSku(customerCode, o.getSku());
					Object[] obj = {
							i+1,
							o.getCustomer().getCustomerName(),
							o.getShopName(),
							o.getWarehouse().getGroupName(),
							o.getBatchCode(),
							o.getTaskCode(),
							o.getOrderno(),
							o.getOrderType(),
							o.getSku(),
							goodsSku.getSkuName(),
							o.getExpressNo(),
							o.getCustomerOrderno(),
							o.getFromno(),
							o.getAddres(),
							o.getNum(),
							o.getPri(),
							cancelOrderStr,
							o.getCreateTime(),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					logger.error("error",e);
				}
			}
			 */
			/** begin modify 20160616 lianghe.yuan */
			
			
			/** begin modify 导出修改 20160616 */
			/** 导出数据 */
			/** begin comment 20160616 old */
//			String[] title = { "序号", "商家","店铺","仓库","批次号", "任务号","订单号","订单类型", "SKU","商品名称","快递单号","商家订单号","来源订单号","地址","数量","单价","订单状态","创建时间"};
//			String filepath = customerCode+"_"+warehouseCode+".xls";
//			String title_page="出库订单明细";
//			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
//			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
//			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
//			byte[] fb = new byte[f.available()];
//			f.read(fb);
//			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
//			output =((HttpServletResponse)response).getOutputStream();
//			int by = 0;
//			while ((by = bais.read()) != -1) {
//				output.write(by);
//			}
//			output.flush();
			/** end comment 20160616 old */
			
			/** begin new 2016-06-16 */
            response.setContentType("application/octet-stream");
			String[] titles = { "序号", "商家","店铺","仓库","批次号", "任务号","订单号","订单类型", "SKU","商品名称","快递单号","商家订单号","来源订单号","地址","数量","单价","订单状态","创建时间"};
            String fileName = new String((customerCode + "_" +  warehouseCode + ".xls").getBytes("GBK"), "ISO8859-1");
            ((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename=" + fileName);
            
            String pageTitle="出库订单明细";
            
            output = response.getOutputStream();
            ExcelStUtil.export(output, DateFormatUtils.format(now, "yyyyMMddhhmmss"), pageTitle, titles, list);
            /** end new 2016-06-16 */
            
			/** end modify 导出修改 20160616 */
		} catch (Exception e) {
			logger.error("expDetail_order case error",e);
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	//////////////////////////////////////////////////////////拣货明细///////////////////////////////////////////////////////////////////////
		
	//查询拣货明细
	@RequestMapping(value = "v2_queryDetail_work",method=RequestMethod.POST)
	public String queryDetail_work(Model model, ServletRequest request) {
		try {
			
			//Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
		    Map<String, Object> param = Servlets.getParametersStartingWith(request, "");
			String customerCode=(String)param.get("customerCode");
			String warehouseCode=(String)param.get("warehouseCode");
			String batchCode=(String)param.get("batchCode");
			String taskCode=(String)param.get("taskCode");
			String sku=(String)param.get("sku");
			
			//时间筛选
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			//筛选时间为空时，不查询直接返回
			if(StringUtils.isEmpty(fromDateStr) || StringUtils.isEmpty(toDateStr)){
				return "instorage/outstorageInfo_detail_work";
			}
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			param.put("status", "countStock");
//			param.put("cancelStatus", "ok");
			
			//拣货明细
			List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
			model.addAttribute("orderList", orderList);
			model.addAttribute("_customerCode", customerCode);
			model.addAttribute("_warehouseCode", warehouseCode);
			model.addAttribute("_fromDate", fromDateStr);
			model.addAttribute("_toDate", toDateStr);
			model.addAttribute("_batchCode", batchCode);
			model.addAttribute("_taskCode", taskCode);
			model.addAttribute("_sku", sku);
			
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		
		return "instorage/outstorageInfo_detail_work";
	}
	
	

	/**
	 * 导出_拣货明细
	 */
	@RequestMapping(value = "expDetail_work")
	public String expDetail_work(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//拣货信息统计
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			//筛选时间为空时，不查询直接返回
			if(StringUtils.isEmpty(fromDateStr) || StringUtils.isEmpty(toDateStr)){
				return null;
			}
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			param.put("status", "countStock");
//			param.put("cancelStatus", "ok");
			List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < orderList.size(); i++) {
				try {
					WorkOrder o=orderList.get(i);
					Object[] obj = {
							i+1,
							o.getCustomerCode(),
							o.getWarehouseCode(),
							o.getBatchCode(),
							o.getTaskCode(),
							o.getOrder().getOrdeno(),
							o.getGoodsInfo(),
							o.getStockInfo(),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					logger.error("error",e);
				}
			}
			
			/** 导出数据 */
			String[] title = { "序号", "商家","仓库","批次号", "任务号","订单号", "商品信息","拣货信息"};
			String filepath = "拣货明细.xls";
			String title_page="拣货明细";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
		
	
}
